package com.qf.realm;

import com.qf.entity.User;
import com.qf.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 作者: 王鑫
 * 项目名: jxc1
 * 时间:2019/12/4  20:46
 * 描述:
 */
@Component
public class JxcRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1024);
        this.setCredentialsMatcher(matcher);
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.获取用户名称
        String username = (String) token.getPrincipal();
        //2.根据用户名称查询用户信息
        User user= userService.findByUsername(username);
        //3.判断user是否为null
        if (user == null){
            return null;
        }
        //4.声明simpleAuthenticationInfo
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
        //5.加盐

        //info.setCredentialsSalt(ByteSource.Util.bytes("加盐"));

        //6.返回info

        return info;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }


}
